package com.course.web.component.custom;

import com.course.web.biz.WebClassBiz;
import com.course.web.component.base.BaseEdit;
import com.course.web.component.base.BaseGrid;
import com.course.web.component.base.EditGrid;
import com.course.web.model.ClassItemVM;
import com.course.web.view.TeacherClassView;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.Layout;
import com.vaadin.ui.renderers.DateRenderer;
import com.vaadin.ui.renderers.Renderer;

import java.text.SimpleDateFormat;

/**
 * Created by Justin on 2017/6/15.
 */
@SpringComponent
@ViewScope
public class ClassTodoGrid extends EditGrid<ClassItemVM> {

    private final WebClassBiz classBiz;

    private Button openNext;
    private ClassItemVM next;

    public ClassTodoGrid(WebClassBiz classBiz) {
        super(ClassItemVM.class);
        this.classBiz = classBiz;
    }

    @Override
    protected void doInitMenu(Layout menu) {
        this.openNext = new Button("Start next class");
        menu.addComponent(openNext);
        openNext.addClickListener(event -> open(next));
    }

    @Override
    protected void doInitGrid(BaseGrid<ClassItemVM> grid) {
        Renderer renderer = new DateRenderer(new SimpleDateFormat("MM-dd HH:mm"));
        grid.addColumn(ClassItemVM::getStudent, "Student");
        grid.addColumn(ClassItemVM::getTask, "ClassName");
        grid.addColumn(ClassItemVM::getDateTime, "BeginTime").setRenderer(renderer);
        grid.addColumn(ClassItemVM::getRoom, "RoomID");
        grid.addButton(this::open, "Prepare for class");
    }

    @Override
    protected void doInitEdit(BaseEdit<ClassItemVM> edit) {
        super.doInitEdit(edit);
    }

    private void open(ClassItemVM item) {
        if (item == null) {
            return;
        }
        getUI().getNavigator().navigateTo(TeacherClassView.NAME + "/" + item.getId());
    }

    public void enter(int teacherId) {
        this.next = classBiz.findNextItemByTeacher(teacherId);
        init(classBiz.findItemByTeacher(teacherId));
        openNext.setEnabled(next != null);
    }
}
